package com.css.zfzx.fwsjcj.modules.group.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupEntity;
import com.css.zfzx.fwsjcj.modules.group.repository.FwGroupQueryRepository;
import com.css.zfzx.fwsjcj.modules.group.vo.FwGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.List;

@Repository
@PropertySource("classpath:platform-config.yml")
public class FwGroupQueryRepositoryImpl implements FwGroupQueryRepository {

    @PersistenceContext
    EntityManager entityManager;
    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.taskCode}")
    private String taskCode;
    @Autowired
    private DivisionRepository divisionRepository;
    @Override
    public Page<FwGroupEntity> getPage(HttpServletRequest request, FwGroupVo fwGroupVo, int curPage, int pageSize,String groupType) {
        StringBuilder sql = new StringBuilder("select * from fw_group ");
        StringBuilder whereSql = new StringBuilder("where del_flag = '" + Constant.IS_VALID_YES + "'");
        if (!StringUtils.isEmpty(fwGroupVo.getGroupName())) {
            whereSql.append(" and group_name like :groupName");
        }
        if (!StringUtils.isEmpty(fwGroupVo.getGroupLeader())) {
            whereSql.append(" and group_leader like :groupLeader");
        }
        String userId= PlatformSessionUtils.getUserId();
        DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
        if(!StringUtils.isEmpty(mainDept)) {
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            if(!StringUtils.isEmpty(validDivisionById)) {
                if(!"中华人民共和国".equals(validDivisionById.getDivisionName())) {
                    whereSql.append(" and address like :divisionName");
                }
            }
        }
        whereSql.append(" and ( group_type is null or group_type = '' or group_type = "+groupType+" )");
        StringBuilder order = new StringBuilder(" order by create_time desc");
        Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(order).toString(), FwGroupEntity.class);

        StringBuilder count = new StringBuilder(" select count(*) from fw_group ");
        Query countQuery = entityManager.createNativeQuery(count.append(whereSql).toString());
        if (!StringUtils.isEmpty(fwGroupVo.getGroupName())) {
            nativeQuery.setParameter("groupName", "%" + fwGroupVo.getGroupName() + "%");
            countQuery.setParameter("groupName", "%" + fwGroupVo.getGroupName() + "%");
        }
        if (!StringUtils.isEmpty(fwGroupVo.getGroupLeader())) {
            nativeQuery.setParameter("groupLeader", "%" + fwGroupVo.getGroupLeader() + "%");
            countQuery.setParameter("groupLeader", "%" + fwGroupVo.getGroupLeader() + "%");
        }
        if(!StringUtils.isEmpty(mainDept)) {
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            if(!StringUtils.isEmpty(validDivisionById)) {
                if(!"中华人民共和国".equals(validDivisionById.getDivisionName())) {
                    String divisionName = validDivisionById.getDivisionName();
                    nativeQuery.setParameter("divisionName", "%" + divisionName + "%");
                    countQuery.setParameter("divisionName", "%" + divisionName + "%");
                }
            }
        }

        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        List<FwGroupEntity> resultList = nativeQuery.getResultList();
        BigInteger countNum = (BigInteger) countQuery.getSingleResult();
        Page<FwGroupEntity> page = new PageImpl<>(resultList, pageable, countNum.longValue());
        return page;
    }

    @Override
    public Page<FwGroupEntity> getPageGroup(HttpServletRequest request, FwGroupVo fwGroupVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from fw_group ");
        StringBuilder whereSql = new StringBuilder("where del_flag = '" + Constant.IS_VALID_YES + "'");
        if (!StringUtils.isEmpty(fwGroupVo.getGroupName())) {
            whereSql.append(" and group_name like :groupName");
        }
        if (!StringUtils.isEmpty(fwGroupVo.getGroupLeader())) {
            whereSql.append(" and group_leader like :groupLeader");
        }
        String userId= PlatformSessionUtils.getUserId();
        DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
        if(!StringUtils.isEmpty(mainDept)) {
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            if(!StringUtils.isEmpty(validDivisionById)) {
                if(!"中华人民共和国".equals(validDivisionById.getDivisionName())) {
                    whereSql.append(" and address like :divisionName");
                }
            }
        }
        whereSql.append(" and group_type = 2");
        StringBuilder order = new StringBuilder(" order by create_time desc");
        Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(order).toString(), FwGroupEntity.class);

        StringBuilder count = new StringBuilder(" select count(*) from fw_group ");
        Query countQuery = entityManager.createNativeQuery(count.append(whereSql).toString());
        if (!StringUtils.isEmpty(fwGroupVo.getGroupName())) {
            nativeQuery.setParameter("groupName", "%" + fwGroupVo.getGroupName() + "%");
            countQuery.setParameter("groupName", "%" + fwGroupVo.getGroupName() + "%");
        }
        if (!StringUtils.isEmpty(fwGroupVo.getGroupLeader())) {
            nativeQuery.setParameter("groupLeader", "%" + fwGroupVo.getGroupLeader() + "%");
            countQuery.setParameter("groupLeader", "%" + fwGroupVo.getGroupLeader() + "%");
        }
        if(!StringUtils.isEmpty(mainDept)) {
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            if(!StringUtils.isEmpty(validDivisionById)) {
                if(!"中华人民共和国".equals(validDivisionById.getDivisionName())) {
                    String divisionName = validDivisionById.getDivisionName();
                    nativeQuery.setParameter("divisionName", "%" + divisionName + "%");
                    countQuery.setParameter("divisionName", "%" + divisionName + "%");
                }
            }
        }

        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        List<FwGroupEntity> resultList = nativeQuery.getResultList();
        BigInteger countNum = (BigInteger) countQuery.getSingleResult();
        Page<FwGroupEntity> page = new PageImpl<>(resultList, pageable, countNum.longValue());
        return page;
    }
}
